package com.gosling.cloudspace.config.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gosling.cloudspace.common.constants.CommonCodeEnum;
import com.gosling.cloudspace.common.entity.BaseResult;
import com.gosling.cloudspace.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@RestControllerAdvice(basePackages = {"com.soyoo.yooloanassist"})
@Slf4j
@Order(100)
public class ControllerResponseAdviceAutoConfiguration implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // response是ResultVo类型，或者注释了NotControllerResponseAdvice都不进行包装
        return !(methodParameter.getParameterType().isAssignableFrom(BaseResult.class)
//                || methodParameter.hasMethodAnnotation(NoHandleResponse.class)
        );
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 针对字符串返回,处理响应头
                response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                // 将数据包装在ResultVo里后转换为json串进行返回
                return objectMapper.writeValueAsString(BaseResult.success(data));
            } catch (JsonProcessingException e) {
                log.error("统一返回String字符串异常{}", e.getMessage());
                throw new CommonException(CommonCodeEnum.ERROR);
            }
        }
        return BaseResult.success(data);

    }
}
